<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkContact\Job;

use Hyperf\AsyncQueue\Job;
use Hyperf\Logger\LoggerFactory;
use MoChat\App\WorkContact\Queue\SyncContactQueue;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use Psr\Log\LoggerInterface;

/**
 * 根据企业id同步客户.
 */
class SyncContactByCorpIdJob extends Job
{
    /**
     * @var array
     */
    public $params;

    /**
     * @var WorkEmployeeContract
     */
    private $workEmployeeService;

    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct(array $params)
    {
        $this->params = $params;
    }

    public function handle()
    {
        $corpId = (int) $this->params['corpId'];
        $this->workEmployeeService = make(WorkEmployeeContract::class);
        $loggerFactory = make(LoggerFactory::class);
        $this->logger = $loggerFactory->get(__CLASS__);

        $this->logger->debug(sprintf('同步客户队列开始执行，企业ID:%s', (string) $corpId));
        $this->makeSyncContactListQueue($corpId);
    }

    /**
     * 生产同步客户列表队列.
     */
    private function makeSyncContactListQueue(int $corpId, int $page = 1)
    {
        $perPage = 100;
        $where = [
            'corp_id' => $corpId,
        ];
        $options = [
            'page' => $page,
            'perPage' => $perPage,
        ];

        $employees = $this->workEmployeeService->getWorkEmployeeList($where, ['id', 'wx_user_id'], $options);
        if (empty($employees) || empty($employees['data'])) {
            return;
        }

        // 异步队列处理
        $syncContactQueue = make(SyncContactQueue::class);
        foreach ($employees['data'] as $key => $employee) {
            if (empty($employee['wxUserId'])) {
                continue;
            }

            $this->logger->debug(sprintf('生产同步客户列表队列，企业ID:%s，员工ID:%s', (string) $corpId, (string) $employee['id']));
            $syncContactQueue->syncContactList([
                'corpId' => $corpId,
                'employeeId' => (int) $employee['id'],
                'wxUserId' => $employee['wxUserId'],
            ]);
        }

        if (count($employees['data']) == $perPage) {
            $this->makeSyncContactListQueue($corpId, ++$page);
        }
    }
}
